
#ifndef _Resource_H__
#define _Resource_H__

#include "Common.h"
#include "String.h"
#include "SharedPtr.h"
#include "StringInterface.h"
#include "AtomicWrappers.h"
#include "Object.h"
#include "Threading/AtomicBoolean.h"

#include <boost/thread.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/bind.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/locks.hpp>

#include <sys/syscall.h>
#define res_gettid() syscall(__NR_gettid)


//for resource inner lock
#define WGS_RESOURCE_INNER_MUTEX_NAME resource_inner_mutex
#define WGS_RESOURCE_INNER_MUTEX mutable boost::mutex WGS_RESOURCE_INNER_MUTEX_NAME;
#define WGS_RESOURCE_INNER_LOCK		boost::lock_guard<boost::mutex> wgsResourceInnerMutexLock(WGS_RESOURCE_INNER_MUTEX_NAME);

//for event lock
#define WGS_EVENT_INNER_MUTEX_NAME 	event_inner_mutex
#define WGS_EVENT_INNER_MUTEX 	mutable boost::shared_mutex WGS_EVENT_INNER_MUTEX_NAME;
#define WGS_EVENT_READ_LOCK		boost::shared_lock<boost::shared_mutex>  wgsEventReadInnerMutexLock(WGS_EVENT_INNER_MUTEX_NAME);
//#define WGS_EVENT_WRITE_LOCK		boost::unique_lock<boost::shared_mutex>  wgsEventWriteInnerMutexLock(WGS_EVENT_INNER_MUTEX_NAME);
#define WGS_EVENT_UPGRARD_LOCK		boost::upgrade_lock<boost::shared_mutex>  wgsEventUpgardInnerMutexLock(WGS_EVENT_INNER_MUTEX_NAME);


/*#define WGS_RESOURCE_INNER_LOCK		Log.Debug("ResourceInnerLock","Resource[%u:%u] thread:[%u] Lock:[%s::%u]",mHandle,mType,res_gettid(),__FILE__, __LINE__);	\
		boost::recursive_mutex::scoped_lock wgsResourceInnerMutexLock(WGS_RESOURCE_INNER_MUTEX_NAME);
*/

    	typedef unsigned long ResourceHandle;


	// Forward declaration
	class ManualResourceLoader;
	class ResourceManager;
	class EventableObject;
	class Object;
	class StringInterface;
	class ResourceProxy;
	class Field;

	namespace AIScript {
		class AIScript;
		class AIInterface;
	}


	enum	ResourceType
	{
		ResourceTypeNone		= 0,	
		ResourceTypeUser		= 1,
		ResourceTypeCharacter		= 2,
		ResourceTypeItem		= 3,
		ResourceTypeResv		= 4,	//保留
		//ResourceTypeBattleMap		= 5,
		ResourceTypeChannel		= 6,
		ResourceTypeTown		= 7,
		ResourceTypeCountry		= 8,
		ResourceTypeBattleSocket	= 9,
		ResourceTypeItemModel		= 10,
		ResourceTypeEffectModel		= 11,
		ResourceTypeEffect		= 12,
		ResourceTypeRegion		= 13,
		ResourceTypeWorldSocket		= 14,
		ResourceTypeMail		= 15,
		ResourceTypeTitle		= 16,
		//ResourceTypeWorldMap		= 17,
		ResourceTypeSpawn		= 18,
		ResourceTypeMissionModel	= 19,
		ResourceTypeMission		= 20,
		ResourceTypeCustom		= 50	//用户定制类型
	};

	//资源在协议和数据库中的定义
	enum	ResourceTargetType
	{
		RTT_NONE		= 0,
		RTT_CHARACTER		= 1,   	//角色类型
		RTT_RESV		= 2,	//保留
		RTT_ITEM		= 3,	//物品类型
		RTT_CHANNEL		= 4,	//战场
		RTT_REGION		= 5,	//区域
		RTT_TOWN		= 6,	//城市
		RTT_COUNTRY		= 7,	//国家
		RTT_EFFECT		= 8,	//特效
		RTT_MAIL		= 9,	//邮件
		RTT_USER		= 10,	//用户
		RTT_SPAWN		= 11,	//再生
		RTT_REPORT		= 12,	//游戏报告
		RTT_MISSION		= 13,	//任务
		RTT_OTHER		= 20,	//其他
		RTT_CUSTOM		= 50	//用户自定义
	};

	//资源状态类型
	enum  ResourceStatus
	{
		ResourceStatusNone		= 0,	//无效资源状态
		ResourceStatusDeleted		= 255	//资源删除状态
	};

	enum ResourceEventValue{
		ResourceEvent_None		= 0,	//无效资源事件
		ResourceEvent_Load		= 1,	//资源载入事件
		ResourceEvent_Unload		= 2,	//资源卸载事件
		ResourceEvent_SaveDB		= 3,	//资源数据写入
		ResourceEvent_LoadDB		= 4,	//资源数据载入
		ResourceEvent_Activate		= 5,	//资源激活事件
		ResourceEvent_Update		= 6,	//资源更新事件
		ResourceEvent_WorldLoading	= 7,	//世界资源载入中
		ResourceEvent_WorldLoaded	= 8,	//世界资源载入完毕
		ResourceEvent_WorldReloading	= 9,	//世界服务器资源重新载入
		ResourceEvent_WorldReloaded	= 10,	//世界重新载入结束
		ResourceEvent_ChildUpdate	= 11,	//资源子对象更新事件
		ResourceEvent_AutoSaveEnable	= 20,	//设置资源和子对象自动存放数据
		ResourceEvent_AutoSaveDisable	= 21,	//设置资源子对象不进行自动保存（默认）
		ResourceEvent_Freeze		= 22,	//资源子对象数据冻结
		ResourceEvent_Unfreeze		= 23,	//资源子对象数据可更新（默认）
		ResourceEvent_ServerJoin	= 50,	//服务器连接事件
		ResourceEvent_ServerPart	= 51,	//服务器断开事件
		
		ResourceEvent_ChannelProcess	= 100,	//战场处理中

		ResourceEvent_User		= 1000	//用户定义的资源事件
	};

	enum EevnetReturnFlag
	{
		EVERET_NONE			= 0x00,		//无效返回值
		EVERET_OK 			= 0x01,		//调用成功，无返回值
		EVERET_OBJERR 			= 0x02,		//目标错误
		EVERET_CMDERR 			= 0x04,		//函数名错误
		EVERET_AGVERR 			= 0x08,		//参数错误
		EVERET_ASYN 			= 0x10,		//调用成功，加入异步队列(对父级产生影响
		EVERET_BREAK			= 0x20		//调用中断，不进入事件链
	};

	class ResourceEvent;



	/** Abstract class representing a loadable resource (e.g. textures, sounds etc)
        @remarks
            Resources are data objects that must be loaded and managed throughout
			an application. A resource might be a mesh, a texture, or any other
			piece of data - the key thing is that they must be identified by 
			a name which is unique, must be loaded only once,
			must be managed efficiently in terms of retrieval, and they may
			also be unloadable to free memory up when they have not been used for
			a while and the memory budget is under stress.
		@par
			All Resource instances must be a member of a resource group; see
			ResourceGroupManager for full details.
        @par
            Subclasses must implement:
			<ol>
			<li>A constructor, overriding the same parameters as the constructor
			    defined by this class. Subclasses are not allowed to define
				constructors with other parameters; other settings must be
				settable through accessor methods before loading.</li>
            <li>The loadImpl() and unloadImpl() methods - mSize must be set 
				after loadImpl()</li>
			<li>StringInterface ParamCommand and ParamDictionary setups
			    in order to allow setting of core parameters (prior to load)
				through a generic interface.</li>
			</ol>
    */

	class SERVER_DECL  Resource : public Object,public StringInterface
    	{
	public:
		WGS_AUTO_MUTEX // public to allow external locking
		WGS_RESOURCE_INNER_MUTEX
		WGS_EVENT_INNER_MUTEX

		class Listener
		{
		public:
		   	Listener() {}
			virtual ~Listener() {}

			/** Callback to indicate that background loading has completed.
			@remarks
				This callback is only relevant when a Resource has been
			marked as background loaded (@see Resource::setBackgroundLoaded)
				, and occurs when that loading has completed. The call
				does not itself occur in the thread which is doing the loading;
				when loading is complete a response indicator is placed with the
				ResourceGroupManager, which will then be sent back to the 
				listener as part of the application's primary frame loop thread.
			*/
			virtual void backgroundLoadingComplete(Resource*) {}

			/** Callback to indicate that background preparing has completed.
			@remarks
				This callback is only relevant when a Resource has been
				marked as background loaded (@see Resource::setBackgroundLoaded)
				, and occurs when that preparing (but not necessarily loading) has completed. The call
				does not itself occur in the thread which is doing the preparing;
				when preparing is complete a response indicator is placed with the
				ResourceGroupManager, which will then be sent back to the 
				listener as part of the application's primary frame loop thread.
			*/
			virtual void backgroundPreparingComplete(Resource*) {}
			
		};
		
		/// Enum identifying the loading state of the resource
		enum LoadingState
		{
		    /// Not loaded
		    LOADSTATE_UNLOADED,
		    /// Loading is in progress
		    LOADSTATE_LOADING,
		    /// Fully loaded
		    LOADSTATE_LOADED,
		    /// Currently unloading
		    LOADSTATE_UNLOADING,
		    /// Fully prepared
		    LOADSTATE_PREPARED,
		    /// Preparing is in progress
		    LOADSTATE_PREPARING,
		    /// Loading has error
		    LOADSTATE_ERROR
		};

		typedef boost::signals2::signal<void(ResourceEvent *)>   		ResourceSignal;
		typedef boost::signals2::connection					ResourceConnection;
		typedef boost::signals2::signal<void(ResourceEvent *)>::slot_type	ResourceSlot;
    protected:

		/// Creator
		ResourceManager* mCreator;
		/// Unique name of the resource
        	String mName;
		/// The name of the resource group
		String mGroup;
		/// Numeric handle for more efficient look up than name
        	ResourceHandle mHandle;
		/// Is the resource currently loaded?
        	AtomicScalar<LoadingState> mLoadingState;
		/// Is this resource going to be background loaded? Only applicable for multithreaded
		volatile bool mIsBackgroundLoaded;
		/// The size of the resource in bytes
        	size_t mSize;
		/// Is this file manually loaded?
		bool mIsManual;
		/// Origin of this resource (e.g. script name) - optional
		String mOrigin;
		/// Optional manual loader; if provided, data is loaded from here instead of a file
		ManualResourceLoader* mLoader;
		/// State count, the number of times this resource has changed state
		size_t mStateCount;
	
		// state db count
		size_t mDBCount;
		// auto save db by unload
		bool	mDBAutoSave;
		// freeze Resource database operation
		bool   mDBFreeze;
		// db loaded
		Threading::AtomicBoolean	mDBLoaded;
		// be reloading
		bool	mReloading;

		// resource scipts ai entity
		uint32	mAIEntry;

		//resource type
		ResourceType	mType;

		AIScript::AIScript  	        *m_aiScript;
		AIScript::AIInterface		*m_aiInterface;

		typedef std::list<Listener*> ListenerList;
		ListenerList mListenerList;
		WGS_MUTEX(mListenerListMutex)


		typedef std::map<uint16,Object * >	PropertyMap;
		PropertyMap		mProperties;

		ResourceSignal	 		mResourceSignal;
		ResourceConnection		mResourceConnect;
		ResourceSlot			mResourceSlot;


		/** Protected unnamed constructor to prevent default construction. 
		Resource() 
			: mCreator(0), mHandle(0), mLoadingState(LOADSTATE_UNLOADED), 
			mIsBackgroundLoaded(false),	mSize(0), mIsManual(0), mLoader(0),mStateCount(0),\
			mType(ResourceTypeNone)
		{ 
		}

		*/
		/** Internal hook to perform actions before the load process, but
			after the resource has been marked as 'loading'.
		@note Mutex will have already been acquired by the loading thread.
			Also, this call will occur even when using a ManualResourceLoader 
			(when loadImpl is not actually called)
		*/
		virtual void preLoadImpl(void) {}
		/** Internal hook to perform actions after the load process, but
			before the resource has been marked as fully loaded.
		@note Mutex will have already been acquired by the loading thread.
			Also, this call will occur even when using a ManualResourceLoader 
			(when loadImpl is not actually called)
		*/
		virtual void postLoadImpl(void) {}

		/** Internal hook to perform actions before the unload process.
		@note Mutex will have already been acquired by the unloading thread.
		*/
		virtual void preUnloadImpl(void) {}
		/** Internal hook to perform actions after the unload process, but
		before the resource has been marked as fully unloaded.
		@note Mutex will have already been acquired by the unloading thread.
		*/
		virtual void postUnloadImpl(void) {}

		/** Internal implementation of the meat of the 'prepare' action. 
		*/
		virtual void prepareImpl(void) {}
		/** Internal function for undoing the 'prepare' action.  Called when
		    the load is completed, and when resources are unloaded when they
		    are prepared but not yet loaded.
		*/
		virtual void unprepareImpl(void) {}
			/** Internal implementation of the meat of the 'load' action, only called if this 
			resource is not being loaded from a ManualResourceLoader. 
		*/
		virtual bool loadImpl(void) = 0;
		/** Internal implementation of the 'unload' action; called regardless of
			whether this resource is being loaded from a ManualResourceLoader. 
		*/
		virtual void unloadImpl(void) = 0;
		/** Calculate the size of a resource; this will only be called after 'load' */
		virtual size_t calculateSize(void) const = 0;

		/// Queue the firing of background loading complete event
		virtual void queueFireBackgroundLoadingComplete(void);

		/// Queue the firing of background preparing complete event
		virtual void queueFireBackgroundPreparingComplete(void);

		//load children from database
		virtual bool loadChildrenFromDB(void)	{	return false;	}
    public:
		/** Standard constructor.
		@param creator Pointer to the ResourceManager that is creating this resource
		@param name The unique name of the resource
		@param group The name of the resource group to which this resource belongs
		@param isManual Is this resource manually loaded? If so, you should really
			populate the loader parameter in order that the load process
			can call the loader back when loading is required. 
		@param loader Pointer to a ManualResourceLoader implementation which will be called
			when the Resource wishes to load (should be supplied if you set
			isManual to true). You can in fact leave this parameter null 
			if you wish, but the Resource will never be able to reload if 
			anything ever causes it to unload. Therefore provision of a proper
			ManualResourceLoader instance is strongly recommended.
		*/
		Resource(ResourceManager* creator, const String& name, ResourceHandle handle,
			const String& group, bool isManual = false, ManualResourceLoader* loader = 0);

		/** Virtual destructor. Shouldn't need to be overloaded, as the resource
		    deallocation code should reside in unload()
		    @see
			Resource::unload()
		*/
		virtual ~Resource();


		/** Prepares the resource for load, if it is not already.  One can call prepare()
		    before load(), but this is not required as load() will call prepare() 
		    itself, if needed.  When OGRE_THREAD_SUPPORT==1 both load() and prepare() 
		    are thread-safe.  When OGRE_THREAD_SUPPORT==2 however, only prepare() 
		    is thread-safe.  The reason for this function is to allow a background 
		    thread to do some of the loading work, without requiring the whole render
		    system to be thread-safe.  The background thread would call
		    prepare() while the main render loop would later call load().  So long as
		    prepare() remains thread-safe, subclasses can arbitrarily split the work of
		    loading a resource between load() and prepare().  It is best to try and
		    do as much work in prepare(), however, since this will leave less work for
		    the main render thread to do and thus increase FPS.
		*/
		virtual void prepare();

	     	/** Loads the resource, if it is not already.
			@remarks
				If the resource is loaded from a file, loading is automatic. If not,
				if for example this resource gained it's data from procedural calls
				rather than loading from a file, then this resource will not reload 
				on it's own.
			@param backgroundThread Indicates whether the caller of this method is
				the background resource loading thread. 
				
		*/
		virtual void load(bool backgroundThread = false);

			/** Reloads the resource, if it is already loaded.
			@remarks
				Calls unload() and then load() again, if the resource is already
				loaded. If it is not loaded already, then nothing happens.
			*/
			virtual void reload(void);

		/*database fetch load */
		virtual void fetchLoad(Field * fields,bool backgroundThread = false);

		/** Returns true if the Resource is reloadable, false otherwise.
		*/
		virtual bool isReloadable(void) const
		{
		    return !mIsManual || mLoader;
		}

		/** Is this resource manually loaded?
			*/
		virtual bool isManuallyLoaded(void) const
		{
			return mIsManual;
		}

		/** Unloads the resource; this is not permanent, the resource can be
			reloaded later if required.
        	*/
		virtual void unload(void);

        	/** Retrieves info about the size of the resource.
        	*/
		virtual size_t getSize(void) const
		{ 
		    return mSize; 
		}

		/** 'Touches' the resource to indicate it has been used.
		*/
		virtual void touch(void);

		/** Gets resource name.
		*/
		virtual const String& getName(void) const 
		{ 
		    return mName; 
		}

		virtual ResourceHandle getHandle(void) const
		{
		    return mHandle;
		}

		/* Sets resource handle unsafe, only for resource Objects update.. */
		virtual void setHandle(const ResourceHandle & handle)
		{
			mHandle = handle;
		}

		virtual	ResourceType getType(void) const
		{
			return mType;
		}

		virtual ResourceTargetType getTargetType(void);

		/** Returns true if the Resource has been prepared, false otherwise.
		*/
		virtual bool isPrepared(void) const 
		{ 
				// No lock required to read this state since no modify
		    return (mLoadingState.get() == LOADSTATE_PREPARED); 
		}

		/** Returns true if the Resource has been loaded, false otherwise.
		*/
		virtual bool isLoaded(void) const 
		{ 
				// No lock required to read this state since no modify
		    return (mLoadingState.get() == LOADSTATE_LOADED); 
		}

		virtual bool isLoadError(void) const
		{
			return (mLoadingState.get() == LOADSTATE_ERROR);
		}

		/** Returns whether the resource is currently in the process of
			background loading.
		*/
		virtual bool isLoading() const
		{
			return (mLoadingState.get() == LOADSTATE_LOADING);
		}

		/** Returns the current loading state.
		*/
		virtual LoadingState getLoadingState() const
		{
			return mLoadingState.get();
		}



		/** Returns whether this Resource has been earmarked for background loading.
		@remarks
			This option only makes sense when you have built Ogre with 
			thread support (OGRE_THREAD_SUPPORT). If a resource has been marked
			for background loading, then it won't load on demand like normal
			when load() is called. Instead, it will ignore request to load()
			except if the caller indicates it is the background loader. Any
			other users of this resource should check isLoaded(), and if that
			returns false, don't use the resource and come back later.
		*/
		virtual bool isBackgroundLoaded(void) const { return mIsBackgroundLoaded; }

		/** Tells the resource whether it is background loaded or not.
		@remarks
			@see Resource::isBackgroundLoaded . Note that calling this only
			defers the normal on-demand loading behaviour of a resource, it
			does not actually set up a thread to make sure the resource gets
			loaded in the background. You should use ResourceBackgroundLoadingQueue
			to manage the actual loading (which will call this method itself).
		*/
		virtual void setBackgroundLoaded(bool bl) { mIsBackgroundLoaded = bl; }

		/** Escalates the loading of a background loaded resource. 
		@remarks
			If a resource is set to load in the background, but something needs
			it before it's been loaded, there could be a problem. If the user
			of this resource really can't wait, they can escalate the loading
			which basically pullsthe loading into the current thread immediately.
			If the resource is already being loaded but just hasn't quite finished
			then this method will simply wait until the background load is complete.
		*/
		virtual void escalateLoading();

		/** Register a listener on this resource.
			@see Resource::Listener
		*/
		virtual void addListener(Listener* lis);

		/** Remove a listener on this resource.
			@see Resource::Listener
		*/
		virtual void removeListener(Listener* lis);

		/* add property pointer for any app. , return the index size - 1 */
		virtual size_t addProperty(const uint16 & index,Object * property);
		virtual void removeProperty(const uint16 & index,bool force_delete = true);
		virtual void removeProperty(Object * property,bool force_delete = true);
		virtual size_t	getPropertiesSize(void)	{	return mProperties.size();	}
		virtual Object * getProperty(const uint16 & idx);
		virtual bool propertyExists(const uint16 &idx);
		virtual void removeAllProperties(bool force_deleted = true);

		/// Gets the group which this resource is a member of
		virtual const String& getGroup(void) { return mGroup; }

		/** Change the resource group ownership of a Resource.
		@remarks
			This method is generally reserved for internal use, although
			if you really know what you're doing you can use it to move
			this resource from one group to another.
		@param newGroup Name of the new group
		*/
		virtual void changeGroupOwnership(const String& newGroup);

		/// Gets the manager which created this resource
		virtual ResourceManager* getCreator(void) { return mCreator; }
		/** Get the origin of this resource, e.g. a script file name.
		@remarks
			This property will only contain something if the creator of
			this resource chose to populate it. Script loaders are advised
			to populate it.
		*/
		virtual const String& getOrigin(void) const { return mOrigin; }
		/// Notify this resource of it's origin
		virtual void _notifyOrigin(const String& origin) { mOrigin = origin; }

		/** Returns the number of times this resource has changed state, which 
			generally means the number of times it has been loaded. Objects that 
			build derived data based on the resource can check this value against 
			a copy they kept last time they built this derived data, in order to
			know whether it needs rebuilding. This is a nice way of monitoring
			changes without having a tightly-bound callback.
		*/
		virtual size_t getStateCount() const { return mStateCount; }

		/** Manually mark the state of this resource as having been changed.
		@remarks
			You only need to call this from outside if you explicitly want derived
			objects to think this object has changed. @see getStateCount.
		*/
		virtual void _dirtyState();



		/** Firing of background loading complete event
		@remarks
			You should call this from the thread that runs the main frame loop 
			to avoid having to make the receivers of this event thread-safe.
			If you use Ogre's built in frame loop you don't need to call this
			yourself.
		*/
		virtual void _fireBackgroundLoadingComplete(void);

		/** Firing of background preparing complete event
		@remarks
			You should call this from the thread that runs the main frame loop 
			to avoid having to make the receivers of this event thread-safe.
			If you use Ogre's built in frame loop you don't need to call this
			yourself.
		*/
		virtual void _fireBackgroundPreparingComplete(void);


		virtual bool isDirtyDB(void);
		virtual void _dirtyDB(void);
		virtual void clearDirtyDB(void);

		virtual bool isAutoSaveDB(void);
		virtual void setAutoSaveDB(const bool & set);
		
		virtual bool isFreezeDB(void);
		virtual void setFreezeDB(const bool & set);
	
		virtual bool  SaveDB(void);
		//just load data from db 
		virtual bool  LoadDB(void);
		// reload data from db only
		virtual bool ReloadDB(void);
		//unload data base
		virtual void  UnloadDB(void);
		//if load db return true else load data from database
		virtual bool checkDB(void);
		//fetch database
		virtual bool FetchDB(Field * fields);
		virtual bool checkFetchDB(Field * fields);
		//if resource had children
		virtual bool hasChildren(void)	{	return false;	}

		virtual const uint32 & getUInt32Field(const String & fieldName) const;
		virtual const int32 & getInt32Field(const String & fieldName) const;
		virtual const uint64 & getUInt64Field(const String & fieldName) const;
		virtual const int64 & getInt64Field(const String & fieldName) const;
		
		virtual const float & getFloatField(const String & fieldName) const;
		virtual const double & getDoubleField(const String & fieldName) const;
		virtual const String & getStringField(const String & fieldName);
		virtual const char * getCStringField(const String & fieldName);
		
		virtual bool setUInt32Field(const String & fieldName,const uint32 & value);
		virtual bool setUInt32Field(const String & fieldName,const String & value);
		virtual bool setInt32Field(const String & fieldName,const int32 & value);
		virtual bool setInt32Field(const String & fieldName,const String & value);
		virtual bool setUInt64Field(const String & fieldName,const uint64 & value);
		virtual bool setUInt64Field(const String & fieldName,const String & value);
		virtual bool setInt64Field(const String & fieldName,const int64 & value);
		virtual bool setInt64Field(const String & fieldName,const String & value);
		virtual bool setFloatField(const String & fieldName,const float & value);
		virtual bool setFloatField(const String & fieldName,const String & value);
		virtual bool setDoubleField(const String & fieldName,const double & value);
		virtual bool setDoubleField(const String & fieldName,const String & value);
		virtual bool setStringField(const String & fieldName,const String & value);
	
		virtual const uint32 & getUInt32Field(const uint16 & index) const;
		virtual const int32 & getInt32Field(const uint16 & index) const;
		virtual const uint64 & getUInt64Field(const uint16 & index) const;
		virtual const int64 & getInt64Field(const uint16 & index) const;
		virtual const float & getFloatField(const uint16 & index) const;
		virtual const double & getDoubleField(const uint16 & index) const;
		virtual const String & getStringField(const uint16  & index);
		virtual const char * getCStringField(const uint16 & index);
		
		virtual bool setUInt32Field(const uint16 & index,const uint32 & value);
		virtual bool setInt32Field(const uint16 & index,const int32 & value);
		virtual bool setUInt64Field(const uint16 & index,const uint64 & value);
		virtual bool setInt64Field(const uint16 & index,const int64 & value);
		virtual bool setFloatField(const uint16 & index,const float & value);
		virtual bool setDoubleField(const uint16 & index,const double & value);
		virtual bool setStringField(const uint16 & index,const String & value);


		virtual bool hasResourceField(const String & fieldName);

		virtual const uint32	& getAIEntry(void)	{	return mAIEntry;	}
		virtual void setAIEntry(const uint32 & ai)	{	mAIEntry = ai;		}


        	virtual void CallScriptUpdate(const uint32 & p_time);
		//检查脚本是否可以在指定的时间更新 毫秒
		virtual bool checkScript(const uint32 & p_time,const uint32 & checktime= 100);
		//检查脚本如果间隔大于checktime 则进行更新
		virtual bool checkScriptUpdate(const uint32 & p_time,const uint32 & checktime = 100);
        	virtual AIScript::AIScript * getAIScript(void)    	{       return m_aiScript;      }
        	virtual void    setAIScript(AIScript::AIScript * ai)      {       m_aiScript = ai;        }

		virtual AIScript::AIInterface * getAIInterface(void)	{	return m_aiInterface;	}
		virtual void setAIInterface(AIScript::AIInterface * aii)	{	m_aiInterface = aii;	}


		//事件相关
		const ResourceSignal	 &	getResourceSignal(void)		{	return  mResourceSignal;	}
                const ResourceConnection &	getResourceConnection(void)	{	return 	mResourceConnect;	}
                const ResourceSlot  	 &	getResourceSlot(void)		{	return  mResourceSlot;		}

		void	setResourceConnection(const ResourceConnection & conn)	{	mResourceConnect = conn;	}
		//清除所有事件
		virtual void  clearAllEvents(void);
		//事件处理
		virtual void  HandleEvent(ResourceEvent * event);
		//注册事件
		virtual bool  connectEvent(Resource * res);
		//注销事件
		virtual bool disconnectEvent(Resource * res);
		//发送事件
		virtual uint8 	SendEvent(ResourceEvent * event);
		
		//删除对象本身和相关资源 相关管理器移除
		virtual	void	Delete(void);
		//删除对象本身，并从相关管理器移除 表示数据库为删除标志
		virtual void	Destroy(void);

		inline bool operator<(const Resource & r) const {
			return  mType < r.getType()  || (mType == r.getType() && mHandle < r.getHandle());
		}

	private:
		//创建脚本AI 和脚本AI接口	
		virtual void CreateAIScript(void);
		//删除脚本AI 与脚本AI接口
		virtual void DestroyAIScript(void);
		
		//注册新的脚本AI与脚本AI接口，如果存在旧的脚本接口，则先调用DestroyAIScript 删除原接口
		virtual void RegisterAIScript(AIScript::AIScript * ai,AIScript::AIInterface * aiFace);

    	};

	/** Shared pointer to a Resource.
	@remarks
		This shared pointer allows many references to a resource to be held, and
		when the final reference is removed, the resource will be destroyed. 
		Note that the ResourceManager which created this Resource will be holding
		at least one reference, so this resource will not get destroyed until 
		someone removes the resource from the manager - this at least gives you
		strong control over when resources are freed. But the nature of the 
		shared pointer means that if anyone refers to the removed resource in the
		meantime, the resource will remain valid.
	@par
		You may well see references to ResourcePtr (i.e. ResourcePtr&) being passed 
		around internally within Ogre. These are 'weak references' ie they do 
		not increment the reference count on the Resource. This is done for 
		efficiency in temporary operations that shouldn't need to incur the 
		overhead of maintaining the reference count; however we don't recommend 
		you do it yourself since these references are not guaranteed to remain valid.
	*/
	typedef SharedPtr<Resource> ResourcePtr;
	typedef SharedPtr<Object> ObjectPtr;

	/** Interface describing a manual resource loader.
	@remarks
		Resources are usually loaded from files; however in some cases you
		want to be able to set the data up manually instead. This provides
		some problems, such as how to reload a Resource if it becomes
		unloaded for some reason, either because of memory constraints, or
		because a device fails and some or all of the data is lost.
	@par
		This interface should be implemented by all classes which wish to
		provide manual data to a resource. They provide a pointer to themselves
		when defining the resource (via the appropriate ResourceManager), 
		and will be called when the Resource tries to load. 
		They should implement the loadResource method such that the Resource 
		is in the end set up exactly as if it had loaded from a file, 
		although the implementations will likely differ	between subclasses 
		of Resource, which is why no generic algorithm can be stated here. 
	@note
		The loader must remain valid for the entire life of the resource,
		so that if need be it can be called upon to re-load the resource
		at any time.
	*/
	class  SERVER_DECL ManualResourceLoader
	{
	public:
		ManualResourceLoader() {}
		virtual ~ManualResourceLoader() {}

		/** Called when a resource wishes to load.  Note that this could get
		 * called in a background thread even in just a semithreaded ogre
		 * (OGRE_THREAD_SUPPORT==2).  Thus, you must not access the rendersystem from
		 * this callback.  Do that stuff in loadResource.
		@param resource The resource which wishes to load
		*/
		virtual void prepareResource(Resource* resource) { }

		/** Called when a resource wishes to prepare.
		@param resource The resource which wishes to prepare
		*/
		virtual void loadResource(Resource* resource) = 0;
	};

	class SERVER_DECL  DumyResource :public Resource
	{
	public:
		DumyResource(ResourceManager* creator, const String& name, ResourceHandle handle,
                        const String& group, bool isManual = false, ManualResourceLoader* loader = 0):
				Resource(creator,name,handle,group,isManual,loader) {}
		virtual ~DumyResource() {}
	protected:
		void prepareImpl(void) {}
		/** Destroys data cached by prepareImpl.
		 */
		void unprepareImpl(void) {}
		/// @copydoc Resource::loadImpl
		bool loadImpl(void)	{	return true;	}
		/// @copydoc Resource::postLoadImpl
		void postLoadImpl(void)	{}

		void preUnloadImpl(void) {}
		/// @copydoc Resource::unloadImpl
		void unloadImpl(void) {}
		/// @copydoc Resource::calculateSize
		size_t calculateSize(void) const	{	return 0;	}
	};


	class SERVER_DECL  ResourceProxy
	{
	public:
		virtual ~ResourceProxy(void)	{}
		union {
			struct
			{
				uint32			_handle;
				uint32			_type;
			};
			uint64		_value64;
		};
			
			
		ResourceProxy(void):_handle(0),_type(0) {}

		ResourceProxy(const uint32 & handle,const uint8 & type = 0):_handle(handle),_type(type) { }
		ResourceProxy(const uint64 & value):_value64(value)	{}

		ResourceProxy(const Resource * res){
			if(res)
			{
				_handle = res->getHandle();
				_type = res->getType();
			}
			else
			{
				setNull();
			}
		}

		ResourceProxy(const ResourcePtr & res)
		{
			if(res.isNull())
				setNull();
			else
			{
				this->_handle = res->getHandle();
				this->_type = res->getType();
			}
		}

		inline void setNull(void) {	_value64 = 0; }
		inline bool isNull(void) const	{	return this->_value64 == 0; }

		

		inline ResourceProxy & operator=(const ResourcePtr& r) {
			if(r.isNull())
			{
				setNull();
			}
			else
			{
				this->_handle = r->getHandle();
				this->_type = r->getType();
			}
			return * this;
		}

		inline ResourceProxy & operator=(const Resource * r) {
			if(r)
			{
				this->_handle = r->getHandle();
				this->_type = r->getType();
			}
			else
				setNull();

			return *this;
		}

		inline ResourceProxy & operator=(const ResourceProxy& r) {
			this->_value64 = r._value64;

			return *this;
		}

		inline bool operator==(const Resource * r) const  {
			if(r)
			{
				return this->_handle == r->getHandle() && this->_type == (uint32)r->getType();
			}
			else
				return isNull();
		}

		inline bool operator==(const ResourcePtr & r) const {
			if(r.isNull())
				return isNull();
			else
				return this->_handle == r->getHandle() && this->_type == (uint32)r->getType();
		}

		inline bool operator==(const ResourceProxy & r) const {
			return this->_value64 == r._value64;
		}

		inline bool operator!=(const ResourceProxy & r) const {
			return this->_value64 != r._value64;
		}

		inline bool operator!=(const Resource * r) const {
			if(r == NULL)
			{
				if(this->isNull())
					return true;
				else
					return false;
			}

			return this->_handle != r->getHandle() ||  this->_type != (uint32) r->getType();
		}

		inline bool operator!=(const ResourcePtr & r) const {
			if(r.isNull())
			{
				if(this->isNull())
					return true;
				else
					return false;
			}
			return this->_handle != r->getHandle() ||  this->_type != (uint32)r->getType();
		}


		inline bool operator<(const ResourceProxy & r) const {
			return this->_type < r._type || (this->_type == r._type && this->_handle < r._handle);
		}

		Resource * getResource(void);
		ResourcePtr getResourcePtr(void);

		ResourceTargetType getTargetType(void);

		static ResourceType   getResourceType(const ResourceTargetType & targetType);

	};	



        namespace __gnu_cxx
        {
            template <> struct hash<ResourcePtr>
            {
                size_t operator()( const ResourcePtr _resource ) const
                {
                      return  (size_t)_resource.getPointer();
                }
            };

	   template <> struct hash<ObjectPtr>
           {
		size_t operator()(const ObjectPtr _obj) const
		{
			return (size_t) _obj.getPointer();
		}
	   };

	    template <> struct hash<ResourceProxy>
	    {
		
		size_t operator() ( const ResourceProxy _res) const
		{
			return (size_t) ((_res._type <<27) | _res._handle);
		}
		
	    };
        }

	class ResourceEvent
	{
	public:
		uint16			event_id;	//事件ID
		ResourceProxy		source;		//事件源对象
		ResourceProxy		target;		//事件目标对象
		uint16			flag;		//事件标志 (保留)
		uint8			type;		//事件类型 (保留)
		uint8			ret;		//保存事件返回值
		uint32			idata;
		uint32			idata2;
		uint32			idata3;
		uint32			idata4;
		float			fdata;
		float			fdata2;
		NameValuePairList	data;

		
		ResourceEvent()
		{
			initialize();
		}

		virtual ~ResourceEvent()	{}

		void initialize()
		{
			event_id = ResourceEvent_None;
			source.setNull();
			target.setNull();
			flag = 0;
			type = 0;
			idata = 0;
			idata2 = 0;
			idata3 = 0;
			idata4 = 0;
			fdata = 0;
			fdata2 = 0;
			ret = EVERET_NONE;
			data.clear();
		}	
	};


	bool	checkResourceUplink(const ResourceProxy & item,const ResourceProxy & parents, const ResourceProxy & uplink,const char * moduleName);

#endif
